from model.user_deliver_status import UserDeliverStatus
from sqlalchemy import and_
from  model.user import User
from model.job import Job
from model.job_classes import JobClasses
from service.job_classes_service import JobClassesService

class UserDeliverStatusService:
    def __init__(self, session):
        self.session = session

    def send_resume(self, user_deliver):
        self.session.add(user_deliver)

    def get(self, deliver_id):
        q = self.session.query(UserDeliverStatus) \
            .filter(UserDeliverStatus.deliver_id == deliver_id)
        if q:
            return q.first()
        else:
            return None

    def get_delivers_by_user_id(self, user_id):
        q = self.session.query(UserDeliverStatus) \
            .filter(UserDeliverStatus.user_id == user_id)
        if q:
            return q.all()
        else:
            return None

    def get_send_records(self, user_id, job_id):
        try:
            q = self.session.query(UserDeliverStatus) \
                .filter(and_(UserDeliverStatus.user_id == user_id,
                             UserDeliverStatus.job_id == job_id
                             ))
            if q:
                return q.all()
            else:
                return None
        except Exception as ex:
            raise ex
            return None

    # 获得投递到本公司的简历(本公司发布的职位信息，以及职位下的投递人信息)
    def get_deliver_resume(self, company_id, **kwargs):
        class_service = JobClassesService(self.session)
        class_dict = class_service.get_classes_dict()
        result = []
        q = self.session.query(Job,
                               User.user_id,
                               UserDeliverStatus.deliver_id,
                               User.wx_nick_name,
                               User.header_img,
                               Job.company_id,
                               Job.job_id,
                               Job.job_name,
                               Job.job_status,
                               Job.job_class,
                               UserDeliverStatus.resume_id,
                               UserDeliverStatus.deliver_date,
                               UserDeliverStatus.audit_status,
                               UserDeliverStatus.audit_time,
                               UserDeliverStatus.audit_userid
                               ) \
            .outerjoin(UserDeliverStatus, UserDeliverStatus.job_id == Job.job_id) \
            .outerjoin(User, UserDeliverStatus.user_id == User.user_id) \
            .filter(Job.company_id == company_id)

        res = q.all()
        records = []
        for data in res:
            records.append({
                'deliver_id': data.deliver_id,
                'company_id': data.company_id,
                'user_id': data.user_id,
                'user_name': data.wx_nick_name,
                'job_name': data.job_name,
                'job_id': data.job_id,
                'class_code': data.job_class,
                'class_name': class_dict.get(data.job_class),
                'audit_status': data.audit_status if data.audit_status else 0,
                'audit_time': data.audit_time.strftime('%Y-%m-%d %H:%M:%S') if data.audit_time else '',
                'audit_userid': data.audit_userid if data.audit_userid else '',
                'deliver_date': data.deliver_date.strftime('%Y-%m-%d %H:%M:%S') if data.deliver_date else '',
                'avatar': data.header_img if data.header_img else ''
            })
        ##(name=code):list
        data_dict = {}
        for d in records:
                d_key = str(d.get("job_id")) + "=" + d.get("job_name")
                t_list = data_dict.get(d_key) or []
                if not t_list:
                    t_list.append(d)
                    data_dict[d_key] = t_list
                else:
                    t_list.append(d)

        for key, values in data_dict.items():
                sucess_list = []
                # 未通过,不合适的人数
                failedNum = 0
                if values:
                   for f_data in values:
                       ##投递者必须存在
                       if f_data.get("user_id"):
                       #投递者必须存在
                           if f_data.get("audit_status")==2:
                              failedNum=(failedNum+1)
                           #通过或待审核的人数
                           elif f_data.get("audit_status")==1 or f_data.get("audit_status")==0:
                               #通过的信息
                               sucess_list.append(f_data)
                result.append({
                    "name": key.split("=")[1],
                    "job_id": key.split("=")[0],
                    "failedNum":failedNum,
                    "resume_list": sucess_list
                })
        return result

    # 获取投递未通过的投递信息
    def get_deliver_resume_fail(self, job_id, **kwargs):
        class_service = JobClassesService(self.session)
        class_dict = class_service.get_classes_dict()
        q = self.session.query(Job,
                               User.user_id,
                               UserDeliverStatus.deliver_id,
                               User.wx_nick_name,
                               User.header_img,
                               Job.company_id,
                               Job.job_id,
                               Job.job_name,
                               Job.job_status,
                               Job.job_class,
                               UserDeliverStatus.resume_id,
                               UserDeliverStatus.deliver_date,
                               UserDeliverStatus.audit_status,
                               UserDeliverStatus.audit_time,
                               UserDeliverStatus.audit_userid
                               ) \
            .join(UserDeliverStatus, UserDeliverStatus.job_id == Job.job_id) \
            .join(User, UserDeliverStatus.user_id == User.user_id) \
            .filter(Job.job_id == job_id).filter(UserDeliverStatus.audit_status == 2)

        res = q.all()
        records = []
        for data in res:
            records.append({
                'deliver_id': data.deliver_id,
                'company_id': data.company_id,
                'user_id': data.user_id,
                'user_name': data.wx_nick_name,
                'job_name': data.job_name,
                'job_id': data.job_id,
                'class_code': data.job_class,
                'class_name': class_dict.get(data.job_class),
                'audit_status': data.audit_status if data.audit_status else 0,
                'audit_time': data.audit_time.strftime('%Y-%m-%d %H:%M:%S') if data.audit_time else '',
                'audit_userid': data.audit_userid if data.audit_userid else '',
                'deliver_date': data.deliver_date.strftime('%Y-%m-%d %H:%M:%S') if data.deliver_date else '',
                'avatar': data.header_img if data.header_img else ''
            })
        return records

if __name__ == '__main__':
    # from utils.work_db import Session
    #
    # s = Session()
    # ss = UserDeliverStatusService(s)
    # d_list = ss.get_deliver_resume(company_id=6)
    # print(d_list)
    pass

